package cn.tellfish.studydemo.demo;


import java.util.Random;
import java.util.concurrent.Phaser;

public class PhTest {


    public static void main(String[] args) {
        Phaser phaser = new Phaser() {
            @Override
            protected boolean onAdvance(int phase, int registeredParties) {
                int staffs = registeredParties - 1;
                System.out.println("on advance phase:" + phase + " registeredParties:" + registeredParties);
                return registeredParties == 0;
            }
        };

        Random random = new Random();

        for (int i = 0; i < 3; i++) {
            phaser.register();
            new Thread(() -> {
                try {
                    Thread.sleep(random.nextInt(3000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "完成第一步了" + phaser.arriveAndAwaitAdvance());
                try {
                    Thread.sleep(random.nextInt(3000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "完成第2步了" + phaser.arriveAndAwaitAdvance());
                phaser.arriveAndDeregister();
            }).start();
        }

        phaser.awaitAdvance(0);
        System.out.println("等待第一步");
        phaser.awaitAdvance(1);
        System.out.println("等待第二步");
        phaser.awaitAdvance(2);
        System.out.println("phaser 完成了");

    }


}


